package com.xdap.common.aop;

import com.xdap.common.config.LocalValue;
import com.xdap.common.util.FeishuPluginPropertiesUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.jsoup.internal.StringUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Field;


/**
 * @Modified By wangli 修改时间2018/10/30
 * 代码质量校验
 */
@Slf4j
@Order(1)
@Configuration
@Aspect
public class LocalValueAspect {

    //@Pointcut("@annotation(com.xdap.common.config.LocalValue)")
    @Pointcut("execution(public * com.xdap.fsapproval.*..*.*(..))")
    private void LocalValueAspect() {
        //空实现
    }


    @SneakyThrows
    @Before("LocalValueAspect()")
    public void Before(JoinPoint joinPoint) {
        Object target = joinPoint.getTarget();
        Class<LocalValue> localValueClass = LocalValue.class;
        boolean annotationPresent = target.getClass().isAnnotationPresent(localValueClass);
        if (annotationPresent) {
            Class<?> aClass = target.getClass();
            Field[] fields = aClass.getDeclaredFields();
            for (Field thisField : fields) {
                boolean booField = thisField.isAnnotationPresent(LocalValue.class);

                if (booField) {
                    //
                    LocalValue annotation = thisField.getAnnotation(localValueClass);
                    String value = annotation.value();
                    if (StringUtil.isBlank(value)) {
                        continue;// 如果可获取参数的值为空，则不继续
                    }
                    String realValue = value.substring(value.indexOf("${") + 2, value.indexOf("}"));


                    String property = FeishuPluginPropertiesUtil.getProperty(realValue);
                    thisField.setAccessible(true);
                    // 如果获取不到参数，或者是获取到到的参数为null，则直接替换为空
                    if (property == null) {
                        property = value.replace("${" + realValue + "}", "");
                    } else {
                        property = value.replace("${" + realValue + "}", property);
                    }
                    thisField.set(target, property);
                }

            }
        }
    }
}
